import { React, useEffect, useRef,useState } from 'react'
import * as echarts from "echarts";
import './index.scss'
import { Slider } from 'antd';

export default function Index() {
  const chartRef = useRef(null);
   // 获取本地存储内容
   const wind=JSON.parse(localStorage.getItem('settings')) || {};
  //  console.log(wind,'123');
   const [menu,setMenu]=useState(wind.zoomMode);
   //修改颜色
  const [styles, setstyles] = useState(wind.colorData);
  const [colors, setcolors] = useState(wind.colors);

  const [xData, setxData] = useState([]);
  const [data, setdata] = useState([]);
  const [inputValue1, setInputValue1] = useState(30);
  const [inputValue2, setInputValue2] = useState(0);
  const marks = {
    '-100': {
      style: {
        color: '#fff',
      },
      label: <strong>恶</strong>,
    }, 
    100: {
      style: {
        color: '#fff',
      },
      label: <strong>善</strong>,
    },
  };

  function linepie(){
    let chartInstance = echarts.init(chartRef.current);
    const dataNew = data.map((item, index) => {
      if (index < inputValue1) {
        return item;
      }
      if (["100", "-100"].includes(inputValue2)) {
        return inputValue2
      }
      let range = (1 - (inputValue2 > 0 ? item : -item) / 100);
      let tempVal = range * inputValue2 + item;
      return tempVal > 100 ? 100 : (tempVal < -100 ? -100 : tempVal);
    });
    // console.log(`dataNew`, dataNew);
    chartInstance.clear()
    const option = {
      title: {
        // text: 'Beijing AQI',
        left: '10%',
      },
      tooltip: {
        trigger: 'axis',
      },
      grid: {
        top: '11%',
        right: '13%'
      },
      xAxis: {
        // name: '年龄',
        data: xData,
        axisLine: {
          show: true,
          lineStyle: {
            color: styles[colors][0],
          },
        },
      },
      yAxis: {
        name: '福报',
        min: -110,
        max: 110,
        axisLine: {
          show: true,
          lineStyle: {
            color: styles[colors][0],
          },
        },
      },
      visualMap: {
        show: false,
        type: 'continuous',
        seriesIndex: 0,
        min: -100,
        max: 100,
        outOfRange: {
          color: styles[colors],
        },
        inRange: {
          color: styles[colors]
        }
      },
      series: {
        type: 'line',
        data: dataNew,
        markLine: {
          silent: true,
          label: { show: false },
          // symbolSize: 15 * scale,
          data: [{
            yAxis: -100
          }, {
            yAxis: inputValue2
          }, {
            yAxis: 100
          }]
        },
      },
    };
    chartInstance.setOption(option);
    window.addEventListener("resize", function () {
      chartInstance.resize();
    });
  }
  function throttled1(fn, delay = 500) {
    let oldtime = Date.now()
    return function (...args) {
      let newtime = Date.now()
      if (newtime - oldtime >= delay) {
        fn.apply(null, args)
        oldtime = Date.now()
      }
    }
  }
  useEffect(() => {
    for (let i = 0; i <= 120; i++) {
      xData.push(i);
      data.push(Math.random() * 200 - 100)
    }
  }, []);
  useEffect(() => {

    let message = '云谷禅师曰：' +
      '\n人未能无心（凡人都会起心动念），终为阴阳所缚，安得无数（所以有命运）？' +
      '\n但惟凡人有数（不过只有凡人是这样）。' +
      '\n极善之人。数固拘他不定。极恶之人。数亦拘他不定。（而极善极恶之人才能逃脱命运束缚）';
    if (inputValue2 == 100 || inputValue2 == -100) {
      throttled1(alert(message),2000)
    }

  }, [inputValue2]);



  useEffect(() => {
    linepie()
    if (wind.chartRefreshPeriod) {
      const timer = setInterval(() => {
        linepie();
      }, wind.chartRefreshPeriod * 1000)
      return ()=>  clearInterval(timer)
    }
  });
  //设置定时器

  //三元判断函数
  function Mentime({menu}){
    // console.log('Mentime',menu);
    switch(menu){
      case "stretch":
        return(
          <div id='ech' ref={chartRef} style={{ height: '290px', width: '100%', margin: '0 auto', display: 'inline-block' }}></div>
        );
      case "cover":
        return(
          <div id='ech' ref={chartRef} style={{ height: '310px', width: '80%' ,margin:'0 auto'}}></div>
        );
      case "contain":
        return(
          <div id='ech' ref={chartRef} style={{ height: '27vh', width: '90%' ,margin:'0 auto'}}></div>
        );
      default:
        return (
          <div id="ech" ref={chartRef} style={{ width: "25vw", height: "320px", margin: "0 auto" }}></div>
        );
    }
  }

  const onChange1 = (value) => {
    // console.log('onChange: ', value);
    setInputValue1(value)
  };
  const onChange2 = (value) => {
    // console.log('onChange: ', value);
    setInputValue2(value)
  };
  

  return (
    <div className='right'>
      <h3>福报/运气趋势预测(仅供娱乐)</h3>
      <div className="input-group startTime-input-wrap">
        <label>开始年龄:{inputValue1}</label>
        <Slider className='startTime_slider' max={120} defaultValue={inputValue1} onChange={onChange1} />
      </div>
      <Mentime menu={menu} />
      <div className="input-group blessings-input-wrap">
        <label>付出:{inputValue2}</label>
        <Slider min={-100}
          max={100} marks={marks} vertical defaultValue={inputValue2} onAfterChange={onChange2} style={{ display: 'inline-block' }} />
      </div>
    </div>
  );
}
